package cn.jd.basic.controller;

import cn.jd.basic.util.AjaxResult;
import cn.jd.basic.util.FastdfsUtil;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@RequestMapping("/fastdfs")
public class FastdfsController {
    /*上传*/
    @PostMapping
    public AjaxResult upload(@RequestPart("file") MultipartFile file) throws IOException {
        // 扩展名
        String filename = file.getOriginalFilename();
        String extension = FilenameUtils.getExtension(filename);
        String address = FastdfsUtil.upload(file.getBytes(), extension);
        return  AjaxResult.me().success(address);

    }
    @DeleteMapping
    public AjaxResult delete(@RequestParam(value = "filePath",required = true) String filePath) throws IOException{
        // 因为删除需要组名+图片路径，所以我们需要把前端传递进来的图片路径进行分割
        // /group1/M00/00/05/oYYBAGKCO-6AdKyoAAEOykzR2Hc97_350x350.jpeg
        // 1.得到组名和路径名称
        // 1.1.得到组名
        String pathTmp = filePath.substring(1); // goup1/xxxxx/yyyy
        String groupName =  pathTmp.substring(0, pathTmp.indexOf("/")); //goup1
        // 1.2.得到图片路径
        String remotePath = pathTmp.substring(pathTmp.indexOf("/")+1);// /xxxxx/yyyy
        // 2.调用工具类方法进行删除，传递组名和图片路径名称
        FastdfsUtil.delete(groupName, remotePath);
        // 3.返回成功信息+文件访问路径
        return AjaxResult.me().success();

    }
}
